package com.piece.file.util;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.Includes;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.piece.admin.model.TbSysDict;
import com.piece.admin.service.TbSysDictService;
import com.piece.core.framework.util.basic.SpringUtil;
import com.piece.core.framework.annotation.office.ImageRender;
import com.piece.core.framework.annotation.office.SegmentRender;
import com.piece.core.framework.annotation.office.SelectRender;
import com.piece.core.framework.annotation.office.TableRender;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.framework.util.object.ClassUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.file.model.TbSysFile;
import com.piece.file.service.TbSysFileService;
import com.piece.file.client.FileClientFactory;
import com.piece.module.file.util.word.WordUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

@Slf4j
public class OfficeUtil extends WordUtil {

    private static final FileClientFactory fileClientFactory;

    private static final TbSysFileService tbSysFileService;

    private static final TbSysDictService tbSysDictService;

    static {
        fileClientFactory = SpringUtil.getBean(FileClientFactory.class);
        tbSysFileService = SpringUtil.getBean(TbSysFileService.class);
        tbSysDictService = SpringUtil.getBean(TbSysDictService.class);
    }

    /**
     * 根据docx文档模板生成文件流
     *
     * @param file  模板文件
     * @param data  模型数据
     * @param os    输出流
     * @throws
     */
    public static void generateByTemplate(TbSysFile file, Object data, OutputStream os) throws Exception {
        generateByInputStream(fileClientFactory.get().downloadFile(file), data, os);
    }

    /**
     * 根据docx文档模板生成文件流
     *
     * @param templatePath docx模板文件的路径（不含文件名）
     * @param templateName docx模板文件的名称（不含路径）
     * @param data         模型数据
     * @param os           输出流
     * @throws
     */
    public static void generateByTemplate(String templatePath, String templateName, Object data, OutputStream os) throws Exception {
        // 获取项目路径
        Properties props = System.getProperties();
        String rootPath = props.getProperty("user.dir");
        File desc = new File(rootPath + File.separator + templatePath + File.separator + templateName);
        generateByInputStream(new FileInputStream(desc), data, os);
    }

    /**
     * 根据docx文档模板生成文件流
     *
     * @param inputStream 模板流数据
     * @param data         模型数据
     * @param os            输出流
     * @throws
     */
    public static void generateByInputStream(InputStream inputStream, Object data, OutputStream os) throws Exception {
        Map<String, Object> param = new HashMap<>();
        BeanUtil.beanToMap(data, param);
        ConfigureBuilder configBuilder = Configure.builder();
        generateParam(data, param, configBuilder);
        Configure configure = configBuilder.build();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(param);
        template.write(os);
    }

    private static void generateParam(Object data, Map<String, Object> param, ConfigureBuilder configBuilder) {
        InputStream is = null;
        try {
            Field[] fields = data.getClass().getDeclaredFields();
            LoopRowTableRenderPolicy tableRenderPolicy = new LoopRowTableRenderPolicy();

            for (Field field : fields) {
                field.setAccessible(true);
                if (!ClassUtil.isJavaClass(field.getType())) {
                    Map<String, Object> param_child = new HashMap<>();
                    generateParam(field.get(data), param_child, configBuilder);
                    param.put(field.getName(), param_child);
                }

                // 图片生成器
                ImageRender image = field.getAnnotation(ImageRender.class);
                if (null != image) {
                    if (field.get(data) != null) {
                        int width = image.width();
                        int height = image.height();

                        TbSysFile file = tbSysFileService.findById((String) field.get(data));
                        if (file != null) {
                            is = fileClientFactory.get().downloadFile(file);
                            param.put(field.getName(), Pictures.ofStream(is, PictureType.suggestFileType("." + file.getContentType().toLowerCase())).size(width, height).create());
                            is.close();
                        } else {
                            param.put(field.getName(), null);
                        }
                    } else {
                        param.put(field.getName(), null);
                    }
                }
                // 选择生成器
                SelectRender select = field.getAnnotation(SelectRender.class);
                if (null != select) {
                    List<TbSysDict> dictList = tbSysDictService.findByDicGroup(select.dictType());
                    if (null != dictList) {
                        String value_ = (String) field.get(data);
                        if (StringUtil.isEmpty(value_)) {
                            param.put(field.getName(), "");
                        } else {
                            String text = dictList.stream().map(dict -> {
                                if (dict.getDictValue().equals(value_)) {
                                    dict.setDictLabel(select.selected() + " " + dict.getDictLabel());
                                    dict.setDictLabelEn(select.selected() + " " + dict.getDictLabelEn());
                                } else {
                                    dict.setDictLabel(select.unSelected() + " " + dict.getDictLabel());
                                    dict.setDictLabelEn(select.unSelected() + " " + dict.getDictLabelEn());
                                }
                                return dict;
                            }).map(TbSysDict::getDictLabel).collect(Collectors.joining("  "));
                            param.put(field.getName(), text);
                        }
                    } else {
                        param.put(field.getName(), null);
                    }
                }
                // 表格选择器
                TableRender table = field.getAnnotation(TableRender.class);
                if (null != table) {
                    configBuilder.bind(field.getName(), tableRenderPolicy);
                }
                // 子模板选择器
                SegmentRender segment = field.getAnnotation(SegmentRender.class);
                if (null != segment) {
                    if (StringUtil.isNotEmpty(segment.path())) {
                        String src = WordUtil.class.getResource("/").getPath().substring(1) + segment.path();
                        param.put(field.getName(), Includes.ofLocal(src).setRenderModel((List) field.get(data)).create());
                    } else {
                        TbSysFile file = tbSysFileService.findById(segment.name());
                        param.put(field.getName(), Includes.ofStream(fileClientFactory.get().downloadFile(file)).setRenderModel((List) field.get(data)).create());
                    }
                }
            }
        } catch (Exception e) {
            log.error("转换word模板属性异常：{}", e.getMessage());
        }
    }

    // 清理缓存文件
    public static void deleteTempFile() {
        FileUtil.deleteFiles(FileUtil.getTempPath());
    }
}
